﻿package com.bizmlib.managers
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	
	[Event(name="render", type="flash.events.Event")]
	
	
	public class UIRenderManager extends EventDispatcher
	{
		private static const STATE_STOP:Number = 1;
		private static const STATE_RUN:Number = 2;
		private static const STATE_RENDER:Number = 3;
		private static const STATE_CLEAN:Number = 4;
		
		protected var state:Number;
		protected var target:DisplayObject;
		protected var updatedProperties:Dictionary;
		protected var newProperties:Dictionary;
		
		
		public function UIRenderManager(target:DisplayObject)
		{
			this.target = target;
			updatedProperties = new Dictionary();
			newProperties = new Dictionary();
			state = STATE_STOP;
		}
		
		
		public function activate(propertyName:String = undefined):void
		{
			start(propertyName);
		}
		public function start(propertyName:String = undefined):void
		{
			if(state==STATE_CLEAN)
			{
				return;
			}
			else if(state==STATE_STOP)
			{
				state = STATE_RUN;
				target.addEventListener(Event.ENTER_FRAME, targetEnterFrame);
			}
			if(propertyName)
			{
				setProperty(propertyName);
			}
		}
		public function stop():void
		{
			if(state==STATE_RUN)
			{
				target.removeEventListener(Event.ENTER_FRAME, targetEnterFrame);
				state = STATE_STOP;
			}
		}
		public function clean():void
		{
			stop();
			state = STATE_CLEAN;
			target = null;
			updatedProperties = null;
			newProperties = null;
		}
		public function setProperty(propertyName:String, value:* = null):void
		{
			if(state==STATE_CLEAN)
			{
				return;
			}
			else if(state==STATE_RENDER)
			{
				newProperties[propertyName] = value;
			}
			else
			{
				updatedProperties[propertyName] = value;
			}
		}
		public function checkProperty(propertyName:String, remove:Boolean = false):Boolean
		{
			var checkResult:Boolean = updatedProperties.hasOwnProperty(propertyName);
			if(remove)
			{
				deleteProperty(propertyName);
			}
			return checkResult;
		}
		public function deleteProperty(propertyName:String):void
		{
			delete updatedProperties[propertyName];
		}
		
		
		protected function targetEnterFrame(event:Event):void
		{
			stop();
			
			state = STATE_RENDER;
			
			dispatchEvent(new Event(Event.RENDER, false, true));
			
			for(var propertyName:String in updatedProperties)
			{
				deleteProperty(propertyName);
			}
			
			state = STATE_STOP;
			
			for(var newPropertyName:String in newProperties)
			{
				delete newProperties[newPropertyName];
				start(newPropertyName);
			}
		}
		
		
		override public function toString():String
		{
			return "[UIRenderManager]";
		}
	}
}